import Vue from 'vue'
import {Message} from "element-ui"
import 'normalize.css/normalize.css' // A modern alternative to CSS resets
import "./lib/rem2.js"
// import "lib-flexible" // 移动端 适配
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import locale from 'element-ui/lib/locale/lang/en' // lang i18n
import axios from "axios"
import '@/styles/index.scss' // global CssPartial
// import echarts from 'echarts'

import App from './App'
import store from './store'
import router from './router'
import "./common"
import '@/icons'  // icon
import '@/permission' // permission control
import VueClipboard from 'vue-clipboard2' // 复制插件
// 在Vue原型上加一个 $bus用于事件总线  Vue实例(作为总线)才能.emit事件
Vue.prototype.$bus = new Vue()
// ElSearchTablePagination插件的使用
Vue.use(VueClipboard)

import vueToPdf from '@/plugins/printPDF/index.js'
import vueToImg from '@/plugins/printImg/index.js'
Vue.use(vueToPdf)
Vue.use(vueToImg)

// Vue.prototype.$echarts = echarts


// set ElementUI lang to EN
// Vue.use(ElementUI, { locale })
// 如果想要中文版 element-ui，按如下方式声明
Vue.use(ElementUI,{size:"small"})

Vue.config.productionTip = false
Vue.directive("permission",{
  inserted: function(el, binding) {
    const action = binding.value.action
    // console.log("action",action)
    let userPrivilege =  JSON.parse(sessionStorage.getItem('userPrivilege')) || []
    const currentRight = userPrivilege.filter(item=> item.code==action)
    // console.log("currentRight",currentRight)
    let right = currentRight[0]
    // console.log("right",right)
    if (!!right) {
      // 不具备权限
      const type = right.privilege
      if (type == 'readOnly') {
        el.disabled = true
        el.classList.add('is-disabled')
      }else if(type == 'invisible'){
        el.parentNode.removeChild(el)
      }else{
        // 其他情况正常展示
      }

    }else{
      // 权限不存在直接移除
      el.parentNode.removeChild(el)
    }
  }
})
axios.defaults.timeout = 20000;
Vue.prototype.$get = function (url, config={}) {
  if (!url) throw Error('请核对请求链接是否正确')
  console.log('config', config)
  // const token = window.localStorage.storetoken
  const { params, headers, ...otherConfig } = config
  console.log('params', params)
  const header = Object.assign(headers || {}, {
    // 'Content-Type': 'application/json; charset=utf-8',
    // 'Auth-Token': token,
    // 'Common-Param': getCommonParam()
  })
  return axios.get(url, {
    params,
    headers: header,
    ...otherConfig
  }).catch((error) => { Message.error(error) })
}
// http://172.25.236.83:8088
Vue.prototype.$post = function (url, params, config = {}, type = 1) {
  if (!url) throw Error('请核对请求链接是否正确')
  // const token = window.localStorage.storetoken
  // const {...otherConfig} = config
  let source
  if (type == 1) {
    source = { 'Content-Type': 'application/json; charset=utf-8' } // json 数据
  } else if (type == 2) {
    source = { 'Content-Type': 'multipart/form-data' } // formData表单
  } else {
    source = { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' } // 普通表单
  }
  const header = Object.assign({}, source)
  return axios.post(url, params, {
    headers: header,
    ...config,
    ...source
  }).catch((error) => { Message.error(error) })
}

Vue.prototype.$exportFile = function (url, params) {
  if (!url) throw Error('请核对请求链接是否正确')
  const header = Object.assign({}, {
    headers: {
      "Content-Type":"application/json",
    },
  })
  return axios.post(url, params, {
    headers: header,
    responseType: 'blob',
  }).catch((error) => { Message.error(error) })
}


axios.interceptors.request.use(config => {
  // console.log('request interceptor')
  // const token = storage.get(ACCESS_TOKEN)
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  // const token = localStorage.getItem('token')
  // const token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJob3N0VGVhbSI6IiIsInNpZHMiOiIxMDM2LDEwMjksMTAwMywxMDUxLDEwMDI2Iiwic3ViIjoiSkVUQVVUSCIsInJvbGVJZHMiOiLpu5jorqTop5LoibIiLCJob3N0VHJpYmUiOiIiLCJyZWFsdXNlcm5hbWUiOiJ0ZXN0IiwiZGV2ZWxvcG1lbnRDZW50ZXIiOiIiLCJpYXQiOjE3MDQ4NzU3MDUsInVzZXJuYW1lIjoidGVzdCIsInN0YXR1cyI6IjEifQ.r9wVR7SyX0nSXeoNAfKLE22UNH_icnFqWJ5YXwtpOgM"
  // config.headers.common['Authorization'] = ' Bearer ' + token

  return config
})
axios.interceptors.response.use(function (response) {
  // console.log('response', response)
  if (response.data.code == 20001) {
    return Message.error(response.data.msg || "请求出错请稍后重试")
  }
  return response
}, function (error) {
  const handleError = JSON.parse(JSON.stringify(error))
  console.log('handleError', handleError)
  // console.log("出错了",error.status)
  // console.log("出错了",error.message)
  // console.log("出错了",error.error)
  // if (handleError.response.data.status != 401)

  if(error.code === 'ECONNABORTED' || error.message ===   "Network Error" ||  error.message.includes("timeout")){
    Message({
      message: '请求超时，请稍后重试',
      type: "error",
      duration: 3 * 1000,
    })
  }

  if (handleError.response.status != 401) {
    Message.error(error.message)
  } else {
    console.log("401")
    // store.dispatch("user/logout").then(()=>{
    //   router.replace({ path: '/login' })
    //   setTimeout(() => {
    //     window.location.reload()
    //   })
    // })
    // localStorage.clear()
    // sessionStorage.clear()
    // router.replace({ path: '/login' })
    // setTimeout(() => {
    //   window.location.reload()
    // })
  }

  // Message.error(error.message)
  // if (error.response) {
  //   switch (handleError.response.data.status) {
  //
  //     case 401:

  //       router.replace({
  //         path: '/login',
  //         query: { redirect: router.currentRoute.fullPath }
  //       })
  //       Cookies.remove('user')
  //       Cookies.remove('token')
  //       Cookies.remove('refresh_token')
  //       Cookies.remove('realusername')
  //   }
  // }
  return Promise.reject(error)
})
new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})
